//
//  PhoneLabel.m
//  B2C
//
//  Created by 李小龙 on 2017/8/3.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "PhoneLabel.h"
@interface PhoneLabel()
{
    NSString *_contentStr;
}
@end

@implementation PhoneLabel

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)setText:(NSString *)text {
    [super setText:text];
    _contentStr = text;
    [self validPhoneNum];
}

#pragma mark - <识手机号>
- (void)validPhoneNum{
    //获取字符串中的电话号码
    NSString *regulaStr = @"\\d{3,4}[- ]?\\d{7,8}";
    NSRange stringRange = NSMakeRange(0, _contentStr.length);
    //正则匹配
    NSError *error;
    NSRegularExpression *regexps = [NSRegularExpression regularExpressionWithPattern:regulaStr options:0 error:&error];
    if (!error && regexps != nil) {
        [regexps enumerateMatchesInString:_contentStr options:0 range:stringRange usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            
            //可能为电话号码的字符串及其所在位置
            //           NSString *actionString = [NSString stringWithFormat:@"%@",[_contentStr substringWithRange:result.range]];
            NSRange phoneRange = result.range;
            
            //            NSLog(@"%@-----%@", actionString, NSStringFromRange(phoneRange));
            
            //设置文本中的电话号码显示为蓝色
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:_contentStr];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueTextColor] range:phoneRange];
            self.attributedText = str;
            
            //点击拨打电话
            _phoneStr = [_contentStr substringWithRange:phoneRange];
            //添加手势，可以点击号码拨打电话
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(phoneLink)];
            [self addGestureRecognizer:tap];
            
            
//            UIControl *phoneControl = [self viewWithTag:12345];
//            if (phoneControl == nil) {
//                phoneControl = [[UIControl alloc] initWithFrame:[self boundingRectForCharacterRange:phoneRange andContentStr:_phoneStr]];
//                phoneControl.tag = 12345;
//                [phoneControl addTarget:self action:@selector(phoneLink) forControlEvents:UIControlEventTouchUpInside];
//                [self addSubview:phoneControl];
//            }
        }];
    }
}

#pragma mark-<获取电话号码的坐标>
- (CGRect)boundingRectForCharacterRange:(NSRange)range andContentStr:(NSString *)contentStr
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:contentStr];
    NSDictionary *attrs =@{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    [attributeString setAttributes:attrs range:NSMakeRange(0, contentStr.length)];
    
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributeString];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [textStorage addLayoutManager:layoutManager];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:[self bounds].size];
    textContainer.lineFragmentPadding = 0;
    [layoutManager addTextContainer:textContainer];
    
    NSRange glyphRange;
    
    [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
    
    CGRect rect = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
    CGFloat yOfset =  rect.origin.y;
    rect.origin.y = yOfset + 4;
    
    return rect;
}
#pragma mark-点击拨打电话
- (void)phoneLink {
    if (self.PhoneClick && TextIsNotNil(_phoneStr)) {
        self.PhoneClick(_phoneStr);
    }
}

- (void)phone {
    if (TextIsNotNil(_phoneStr)) {        
        NSString *telStr = [NSString stringWithFormat:@"tel:%@",_phoneStr];
        UIWebView * callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:telStr]]];
        [self addSubview:callWebview];
    }
}


@end
